import {
    createSlice
} from "@reduxjs/toolkit";
import {useSelector} from "react-redux";
import {getInfo, postLogin, postLogout} from "@/api/auth";

const authSlice = createSlice({
    name:"auth",
    initialState:{
        token:localStorage.getItem("token"),
        info:localStorage.info?JSON.parse(localStorage.info):{}
    },
    reducers:{
            clearState(state,{payload}){
                localStorage.clear()
                state.info = state.token = payload
            },
            upInfo(state,{payload}){
              localStorage.setItem("info",JSON.stringify(payload))
              state.info = payload
            },
            upToken(state,{payload}){
                state.token = localStorage.token = payload
            }
    }
})
const {upToken,upInfo,clearState} = authSlice.actions
export const postLoginAsync1 = function (values:any){
    return async (dispatch:any)=>{
        const result = await postLogin(values)
        dispatch(upToken(result.data))
        return result
    }
}
//获取个人信息
export const getInfoAsync = function (){
        return async (dispatch:any,getState:any)=>{
            const state = getState()
            if(state.auth.info.name){
                return
            }
            const result = await getInfo()
            dispatch(upInfo({
                name:result.data.name,
                avatar:result.data.avatar
            }))
        }
}

//退出登陆
export const postLogoutAsync2 = function (){
    return async (dispatch:any)=>{
        const result = await postLogout()
        dispatch(clearState({}))
    }
}

export const useSelectorAuth = ()=>useSelector((state:any) =>state.auth )
export  default  authSlice.reducer
